﻿using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using DevOps.Model;
using Serialize.Library;
using System;
using System.Collections.Generic;

/*
* 命名空间: DevOps.Logic
*
* 功 能： 消息处理逻辑类
*
* 类 名： MessageServiceImpl
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2020/4/8 9:45:42 				Harvey     创建
*
* Copyright (c) 2020 Harvey Corporation. All rights reserved.
*/
namespace DevOps.Logic
{
    /// <summary>
    /// 消息处理逻辑类
    /// </summary>
    public class MessageServiceImpl : OperationLogicImpl, IMessageService
    {
        #region 消息管理相关逻辑

        #region 查询操作
        /// <summary>
        /// 获取消息分页列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<MessageInfoResponse>> LoadPageList(ParametersInfo<MessageQuery> inputInfo)
        {

            var resultInfo = new ResultJsonInfo<List<MessageInfoResponse>>();
            //获取用户登录信息
            var user = GetLoginUserInfo();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysMessageEntity>();

                if (inputInfo.parameters.keyWord.IsNotNullOrEmpty())
                {
                    result.Where(a => a.receiver_name.Contains(inputInfo.parameters.keyWord) || a.sender_name.Contains(inputInfo.parameters.keyWord) || a.title.Contains(inputInfo.parameters.keyWord));
                }
                if (inputInfo.parameters.msg_type > 0)
                {
                    result.Where(p => p.msg_type.Equals(inputInfo.parameters.msg_type));
                }

                result.Where(p => p.receiver_id == user.id || p.sender_id == user.id);

                #region 排序
                if (inputInfo.field.IsNullOrEmpty())
                {
                    inputInfo.field = "create_date";
                }
                if (inputInfo.order.IsNullOrEmpty())
                {
                    inputInfo.order = "desc";
                }
                if (inputInfo.order.ToLower() == "asc")
                {
                    result.OrderBy(inputInfo.field);
                }
                else
                {
                    result.OrderByDescing(inputInfo.field);
                }
                #endregion

                var listInfo = result.PageList(inputInfo.page, inputInfo.limit);
                if (listInfo.Items.Count > 0)
                {
                    #region 发送/接收者判断 加工
                    var templateInfo = listInfo.Items.MapToList<MessageInfoResponse>();
                    foreach (var item in templateInfo)
                    {
                        item.is_sender = item.sender_id == user.id ? true : false;
                        item.is_receiver = item.receiver_id == user.id ? true : false;
                    }
                    #endregion
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = templateInfo;
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 更新操作

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sendInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> SendMessage(MessageSendRequest sendInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();
            var user = GetLoginUserInfo();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = 0;
                con.Transaction(tran =>
                {
                    //如果没有用户信息，直接向所有用户发送信息
                    var userList = new List<SysUserInfoEntity>();
                    if (sendInfo.user_ids == null || sendInfo.user_ids.Count == 0)
                    {
                        userList = tran.QuerySet<SysUserInfoEntity>().Where(p => p.id != user.id).ToList();
                    }
                    else
                    {
                        userList = tran.QuerySet<SysUserInfoEntity>().Where(p => p.id.In(sendInfo.user_ids.ToArray())).ToList();
                    }
                    List<SysMessageEntity> messageList = new List<SysMessageEntity>();
                    foreach (var item in userList)
                    {
                        messageList.Add(new SysMessageEntity()
                        {
                            id = GuidHelper.GetGuid(),
                            receiver_id = item.id,
                            receiver_name = item.name,
                            sender_id = user.id,
                            sender_name = user.name,
                            msg_type = (int)MessageType.DialogueInfo,
                            title = sendInfo.title,
                            content = sendInfo.content,
                            status = (int)MessageStatus.Unread
                        });
                    }
                    result = tran.CommandSet<SysMessageEntity>().Insert(messageList);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "发送成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.MessageManage, $"发送消息成功，发送对象：{JsonHelper.ToJson(sendInfo.user_ids)}");
                    }
                    else
                    {
                        resultInfo.Msg = "发送失败！";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 读取信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<MessageInfoResponse> ReadMessage(string id)
        {

            var resultInfo = new ResultJsonInfo<MessageInfoResponse>();

            if (id.IsNotNullOrEmpty())
            {
                using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
                {
                    var result = 0;
                    con.Transaction(tran =>
                    {
                        var messageInfo = tran.QuerySet<SysMessageEntity>().Where(p => p.id.Equals(id)).Get();

                        messageInfo.status = (int)MessageStatus.AlreadyRead;

                        result = tran.CommandSet<SysMessageEntity>().Update(messageInfo);

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "发送成功！";
                            resultInfo.Data = messageInfo.MapTo<MessageInfoResponse>();

                            AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.MessageManage, $"读取信息成功，读取对象：{id}");
                        }
                        else
                        {
                            resultInfo.Msg = "发送失败！";
                        }
                    });
                }
            }
            else
            {
                resultInfo.Msg = "id不能为空！";
            }
            return resultInfo;
        }

        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="modifyInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(MessageModifyRequest modifyInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = 0;
                var messageInfo = con.QuerySet<SysMessageEntity>().Where(p => p.id == modifyInfo.id).Get();

                if (messageInfo != null)
                {
                    messageInfo.title = modifyInfo.title;
                    messageInfo.content = modifyInfo.content;
                    result = con.CommandSet<SysMessageEntity>().Update(messageInfo);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "修改信息成功！";

                        AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.MessageManage, $"修改消息信息:{JsonHelper.ToJson(modifyInfo)}");
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 物理删除消息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> ids)
        {

            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //删除
                var result = con.CommandSet<SysMessageEntity>().Where(p => p.id.In(ids.ToArray())).Delete();
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "删除成功！";
                    AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.MessageManage, $"物理删除消息成功，物理删除消息信息：{JsonHelper.ToJson(ids)}");
                }
                else
                {
                    resultInfo.Msg = "删除失败！";
                }
            }
            return resultInfo;
        }

        #endregion

        #endregion

        #region 主页面消息相关逻辑

        /// <summary>
        /// 获取对应时间段类，自己的总的消息，未读消息数量
        /// </summary>
        /// <param name="beginTime">起始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public ResultJsonInfo<MessageMyselfCountResponse> LoadMyselfMessageCount(DateTime beginTime, DateTime endTime)
        {

            var resultInfo = new ResultJsonInfo<MessageMyselfCountResponse>();
            //获取用户登录信息
            var user = GetLoginUserInfo();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysMessageEntity>();

                if (beginTime == null)
                {
                    beginTime = DateTime.Now.AddDays(-7);
                }
                if (endTime == null)
                {
                    endTime = DateTime.Now;
                }

                var messageInfo = result.Where(p =>  p.receiver_id == user.id && p.is_deleted == false && p.create_date >= beginTime && p.create_date <= endTime)
                                        .ToList(p => new SysMessageEntity()
                                        {
                                            id = p.id,
                                            status = p.status
                                        });
                if (messageInfo.Count > 0)
                {
                    resultInfo.Data = new MessageMyselfCountResponse()
                    {
                        total = messageInfo.Count,
                        unread_count = messageInfo.FindAll(p => p.status == (int)MessageStatus.Unread).Count
                    };
                    resultInfo.Code = ActionCodes.Success;
                }
                else
                {
                    resultInfo.Data = new MessageMyselfCountResponse();
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }


        /// <summary>
        /// 获取对应时间段内，自己未读消息
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<MessageInfoResponse>> LoadUnreadByTime(DateTime beginTime, DateTime endTime)
        {

            var resultInfo = new ResultJsonInfo<List<MessageInfoResponse>>();
            //获取用户登录信息
            var user = GetLoginUserInfo();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SysMessageEntity>();

                if (beginTime == null)
                {
                    beginTime =DateTime.Now.AddDays(-7);
                }
                if (endTime == null)
                {
                    endTime = DateTime.Now;
                }
                var messageInfo = result
                    .Where(p =>p.receiver_id == user.id && p.status == (int)MessageStatus.Unread && p.create_date>=beginTime&& p.create_date<= endTime)//
                    .OrderByDescing(p => p.create_date)
                    .ToList();

                if (messageInfo.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = messageInfo.MapToList<MessageInfoResponse>();
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }
        #endregion
    }
}
